package com.tencent.org.controller;

import com.tencent.basic.util.AjaxResult;
import com.tencent.basic.util.PageList;
import com.tencent.org.domain.Department;
import com.tencent.org.query.DepartmentQuery;
import com.tencent.org.service.DepartmentService;
import com.tencent.system.annotation.PreAuthorize;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
@Api(value = "部门接口类",description = "部门接口类")
@RestController // 相当于controler + responsbody
@RequestMapping("/department")
public class DepartmentController  {

    @Autowired
    private DepartmentService departmentService;

    @ApiOperation(value = "查询所有")
    @GetMapping

    public List<Department> findAll(){
        return departmentService.findAll();
    }

    // http//localhost:8080/department/1  Restful风格
    @ApiOperation(value = "通过id查询")
    @GetMapping("/{id}")
    public Department findById(@PathVariable("id")Long id){
        return departmentService.findById(id);
    }

    @ApiOperation(value = "通过id删除")
    @DeleteMapping("/{id}")
    @PreAuthorize(name = "部门删除", sn = "department:delete")
    public AjaxResult del(@PathVariable("id")Long id){
        try {
            departmentService.del(id);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败");
        }
    }

    @ApiOperation(value = "添加修改")
    @PutMapping
    public AjaxResult addOrUpdate(@RequestBody Department department){
        try {
            if (department.getId() == null){
                departmentService.add(department);
                return new AjaxResult();
            }else {
                departmentService.update(department);
                return new AjaxResult();
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "操作失败");
        }
    }

    @ApiOperation(value = "分页接口")
    @PostMapping
    @PreAuthorize(name = "部门分页", sn = "department:list")
    public PageList<Department> queryPage(@RequestBody DepartmentQuery departmentQuery){
        return departmentService.queryPage(departmentQuery);
    }

    @ApiOperation(value = "批量删除接口")
    @PatchMapping
    @PreAuthorize(name = "部门批量删除", sn = "department:patchDel")
    public AjaxResult patchDel(@RequestBody List<Long> ids){
        try {
            departmentService.patchDel(ids);
            return new AjaxResult();
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(false, "删除失败");
        }
    }

    @ApiOperation(value = "查询部门树")
    @GetMapping("/departmentTree")
    public List<Department> departmentTree(){
        return departmentService.departmentTree();
    }
}
